package com.jn.algorithm.day023.question74;

import java.util.Arrays;

/**
 * @author 江南大学1033190417
 * @date 2022/5/14 10:56
 */
public class Solution {
    //二分搜索
    public boolean searchMatrix(int[][] matrix, int target) {
        int m = matrix.length;
        int n = matrix[0].length;
        //先二分搜索找到目标所在的行
        int l = -1, r = m - 1;
        while (l < r) {
            int mid = (r - l + 1) / 2 + l;
            if (matrix[mid][0] == target) {
                return true;
            } else if (matrix[mid][0] > target) {
                r = mid - 1;
            } else {
                l = mid;
            }
        }
        if (l < 0) {
            return false;
        }
        //对行再二分查找
        int left = 0, right = n - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (matrix[l][mid] == target) {
                return true;
            } else if (matrix[l][mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] matrix = new int[][]{
//                {1, 3, 5, 7},
//                {10, 11, 16, 20},
//                {23, 30, 34, 50}
                {1}
        };
        System.out.println(solution.searchMatrix(matrix, 0));
    }
}
